define(function (require, exports, module) {
    var $ = require("jquery");
    require("jqtree");
    var angular = require("angular");

    angular
        .module('ProjTreeSelector', [])
        .directive("uiProjTree", ['$timeout','$rootScope', function ($timeout,$rootScope) {
            return {
                //require: "ngModel",
                restrict: "AE",
                scope: {
                    "projs": "=projs",
                    "value": "=ngModel"
                },
                link: function (scope, el, attrs) {

                    var getName = function (node) {
                        var names = [];
                        while (node && node.parent) {
                            names.unshift(node.name);
                            node = node.parent;
                        }

                        return names.join('-');
                    };

                    scope.selects = {}
                    var $rTree = $(el[0])
                        .tree({
                            dragAndDrop: false,
                            useContextMenu: false,
                            selectable: true,
                            autoOpen: 1, //展开级别
                            //创建节点时
                            onCreateLi: function (node, $li) {
                                var id = node.id;
                                if (node.is_init === "0") {
                                    var tip;
                                    try {
                                        if (!node.authorize || !node.authorize.applicationCode.length) {
                                            tip = '该项目未授权任何应用，不能进行初始化';
                                        } else if (node.authorize.applicationCode.length == 1 && node.authorize.applicationCode[0] =="5009" ) {
                                            tip = '该项目只授权了微楼书，不能进行初始化';
                                        } else {
                                            if (!node.authorize.token) {
                                                var auths = [];
                                                angular.forEach(node.authorize.applicationCode,function(app){
                                                    auths.push(scope.$parent.apps[app]);
                                                });
                                                tip = '该项目所授权的应用(' + auths.join(',') + ')还未绑定公众号，不能进行初始化';
                                            }
                                        }
                                    } catch (err) {
                                        
                                    }
                                    if (tip) {
                                        $li.find('div').after('<div class="tooltipsy_box" style="display:none;"><div class="tooltipsy">' + tip + '</div></div>').hover(function(){
                                            $(this).next().toggle().css({
                                                top: ($(this).offset().top + 40) + "px"
                                            })
                                        })
                                    }
                                    $li.find('span').after('<span class="checkbox fr"><input id="' + id + '" type="checkbox" value=""' + (tip ? 'disabled' : '' )+ '><label for="' + id + '">&nbsp;</label></span>');
                                } else if (node.is_init === "1") {
                                    $li.find('span').after('<i class="icon-datainit-tip success-init-icon mt10 fr"></i>');
                                }

                                if (node.type === 0) {
                                    if (node.parentId) {
                                        $li.find('span.jqtree_common').prepend('<i class="icon-datainit group-init-icon"></i>');

                                    } else {
                                        $li.find('span.jqtree_common').prepend('<i class="icon-datainit company-init-icon"></i>');
                                    }
                                }
                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            },
                            onCanSelectNode: function (node) {
                                return !node.children || node.children.length == 0;
                            }
                        })
                        .on('tree.click', function (e) {
                            var target = $(e.click_event.target);

                            if (!target.is('label')) return;

                            var $li = $(e.node.element);

                            var chb = target.parent().find('input[type="checkbox"]')[0];
                            var checked = !chb.checked;
                            var curId = e.node.id;
                          
                            if ($(chb).attr('disabled')) {
                                return;
                            }
                            if ($li.find('ul').length) {
                                $li.find('ul').find('input[type="checkbox"]').each(function (i, item) {
                                    item.checked = checked;

                                    var id = $(item).attr('id');
                                    if (checked) {
                                        var data = e.node.children[i];
                                        scope.selects[id] = angular.extend({
                                            id: data.id,
                                            name: getName(data),
                                            authorize: data.authorize
                                        });
                                    } else {
                                        delete scope.selects[id];
                                    }

                                    scope.selects = scope.selects;
                                });
                            } else {
                                var $parent = $(e.node.parent.element);
                                var $parentCheckbox = $parent.children('div').find('input[type="checkbox"]');

                                if ($parentCheckbox.length) {
                                    if (!checked) {
                                        $parentCheckbox[0].checked = checked;
                                    } else {
                                        var allChecked = true;
                                        var checkboxes = $parent.children('ul').find('input[type="checkbox"]');

                                        for (var i = 0; i < checkboxes.length; i++) {
                                            var checkbox = checkboxes[i];

                                            if (!checkbox.checked && $(checkbox).attr('id') !== e.node.id) {
                                                allChecked = false;
                                                break;
                                            }
                                        }

                                        $parentCheckbox[0].checked = allChecked;
                                    }
                                }

                                if (checked) {
                                    var data = e.node;
                                    scope.selects[curId] = angular.extend({
                                        id: data.id,
                                        name: getName(data),
                                        authorize: data.authorize
                                    });
                                } else {
                                    delete scope.selects[curId];
                                }

                            }

                            $timeout(function () {
                                scope.value = JSON.stringify(scope.selects);
                            });
                        });

                    scope.$watch("projs", function (newValue, oldValue) {
                        if (!newValue) {
                            return;
                        }
                        
                        var fixedData = function(projData) {
                            for(var i = 0; i < projData.length; i++) {  
                                var proj = projData[i];
                                proj.name = proj.name || proj.ProjName;
                                proj.id = proj.id || proj.p_projectId;
                                
                                if (proj.childNodes && proj.childNodes.length) {
                                    proj.children = fixedData(proj.childNodes);
                                }
                            }
                            
                            return projData;
                        }
                        
                        $rTree.tree('loadData', fixedData(newValue));
                    });

                    scope.$on('delProj', function (e, proj) {
                        var checkbox = $rTree.find('#' + proj.id);
                        checkbox[0].checked = false;
                        delete scope.selects[proj.id];
                        try {
                            checkbox.closest('li').parent().parent().children('div').find('input[type=checkbox]')[0].checked = false;
                        } catch (e) {

                        }
                    });

                }
            };

        }])
});